import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:xrenovation/api/auth.api.dart';
import 'package:xrenovation/api/user.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/utils/storage.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';
import 'package:xrenovation/widgets/shadow_card.dart';
import 'package:xrenovation/widgets/theme_switcher.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoggingIn = false;
  bool _keepSignedIn = false;
  bool _showPassword = false;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return Scaffold(
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child: Stack(
          children: [
            // 背景层
            Positioned.fill(child: Container(decoration: BoxDecoration(color: colorScheme.surface))),

            // 内容层
            Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 24),
                child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 384),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildLogoHeader(localizations, theme),
                      const SizedBox(height: 30),
                      _buildLoginCard(localizations, theme),
                      const SizedBox(height: 50),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  Widget _buildDivider(AppLocalizations localizations, ThemeData theme) {
    final colorScheme = theme.colorScheme;

    return Row(
      children: [
        Expanded(child: Divider(color: colorScheme.onSurface.withOpacity(0.1), thickness: 1)),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Text(
            localizations.translate('other_log_way'),
            style: theme.textTheme.bodySmall?.copyWith(color: colorScheme.onSurface.withOpacity(0.6)),
          ),
        ),
        Expanded(child: Divider(color: colorScheme.onSurface.withOpacity(0.1), thickness: 1)),
      ],
    );
  }

  Widget _buildLoginCard(AppLocalizations? localizations, ThemeData theme) {
    final colorScheme = theme.colorScheme;
    final textTheme = theme.textTheme;

    return ShadowCard(
      child: Form(
        key: _formKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题和描述
            Text(
              localizations!.translate('sign_in_title'),
              style: textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 8),
            Text(
              localizations.translate('sign_in_description'),
              style: textTheme.bodyMedium?.copyWith(color: colorScheme.onSurface.withOpacity(0.6)),
            ),

            // 表单字段
            const SizedBox(height: 24),
            CustomTextField(
              controller: _emailController,
              label: localizations.translate('email'),
              hintText: localizations.translate('email_hintText'),
              hiddenErrorTip: true,
              keyboardType: TextInputType.emailAddress,
              suffixIcon: Icon(Icons.email_outlined, color: colorScheme.onSurface.withOpacity(0.6)),
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return '';
                  // return localizations.translate('email_required');
                }
                if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                  return '';
                  // return localizations.translate('email_invalid');
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            CustomTextField(
              controller: _passwordController,
              keyboardType: TextInputType.visiblePassword,
              label: localizations.translate('password'),
              hintText: localizations.translate('pwd_hintText'),
              obscureText: !_showPassword,
              hiddenErrorTip: true,
              suffixIcon: IconButton(
                icon: Icon(
                  _showPassword ? Icons.visibility : Icons.visibility_off,
                  color: colorScheme.onSurface.withOpacity(0.6),
                ),
                onPressed: () {
                  setState(() {
                    _showPassword = !_showPassword;
                  });
                },
              ),
              linkActionText: localizations.translate('forgot_password'),
              linkAction: () {
                Navigator.pushNamed(context, AppRoutes.reset);
              },
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return '';
                  // return localizations.translate('password_required');
                }
                if (value.length < 8) {
                  return '';
                  // return localizations.translate('password_length');
                }
                return null;
              },
            ),

            // keep signed
            const SizedBox(height: 16),
            Row(
              children: [
                Checkbox(
                  value: _keepSignedIn,
                  onChanged: (value) {
                    setState(() {
                      _keepSignedIn = value ?? false;
                    });
                  },
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  fillColor: WidgetStateProperty.resolveWith<Color>((states) {
                    if (states.contains(WidgetState.selected)) {
                      return colorScheme.primary;
                    }
                    return Colors.transparent;
                  }),
                ),
                Text(
                  localizations.translate('keep_signed'),
                  style: textTheme.bodyMedium?.copyWith(color: colorScheme.onSurface.withOpacity(0.6)),
                ),
              ],
            ),

            // 登录按钮
            const SizedBox(height: 24),
            CustomButton(title: localizations.translate('sign_in'), isLoading: _isLoggingIn, onTap: _handleLogin),

            // 分隔线
            const SizedBox(height: 24),
            _buildDivider(localizations, theme),

            // 社交登录按钮
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: _buildSocialLoginButton(
                    icon: SvgPicture.asset(
                      'assets/icons/Google.svg',
                      width: 16,
                      height: 16,
                      color: colorScheme.primary,
                    ),
                    // label: localizations.translate('sign_in_with_google'),
                    onPressed: () => _handleSocialLogin('google'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildSocialLoginButton(
                    icon: SvgPicture.asset('assets/icons/Apple.svg', width: 20, height: 20, color: colorScheme.primary),
                    // label: localizations.translate('sign_in_with_apple'),
                    onPressed: () => _handleSocialLogin('apple'),
                  ),
                ),
              ],
            ),

            // 注册链接
            const SizedBox(height: 24),
            Center(
              child: InkWell(
                onTap:
                    _isLoggingIn
                        ? null
                        : () {
                          Navigator.pushNamed(context, AppRoutes.register);
                        },
                borderRadius: BorderRadius.circular(4),
                child: Padding(
                  padding: const EdgeInsets.all(4),
                  child: RichText(
                    text: TextSpan(
                      text: localizations.translate('dont_have_account'),
                      style: textTheme.bodyMedium?.copyWith(color: colorScheme.onSurface.withOpacity(0.6)),
                      children: [
                        TextSpan(
                          text: localizations.translate('sign_up'),
                          style: textTheme.bodyMedium?.copyWith(
                            color: colorScheme.primary,
                            fontWeight: FontWeight.w600,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLogoHeader(AppLocalizations? localizations, ThemeData theme) {
    final colorScheme = theme.colorScheme;
    final textTheme = theme.textTheme;

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          'assets/images/logo.png',
          width: 52,
          height: 52,
          errorBuilder:
              (context, error, stackTrace) => Icon(Icons.home_work_outlined, size: 52, color: colorScheme.primary),
        ),
        const SizedBox(width: 16),
        Text(
          localizations!.translate('app_title'),
          style: textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.w700, color: colorScheme.primary),
        ),
        const SizedBox(width: 16),
        const ThemeSwitcher(),
      ],
    );
  }

  Widget _buildSocialLoginButton({required Widget icon, String? label, required VoidCallback onPressed}) {
    final hasLabel = label != null && label.isNotEmpty;

    return OutlinedButton(
      onPressed: onPressed,
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
        minimumSize: const Size(100, 48),
        side: BorderSide(color: Theme.of(context).colorScheme.outline.withOpacity(0.2), width: 1),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        backgroundColor: Colors.transparent,
      ),
      child:
          hasLabel
              ? Row(mainAxisSize: MainAxisSize.min, children: [icon, const SizedBox(width: 8), Text(label)])
              : Center(child: icon),
    );
  }

  Future<void> _handleLogin() async {
    if (_isLoggingIn) return;

    if (_formKey.currentState?.validate() ?? false) {
      try {
        setState(() => _isLoggingIn = true);

        final data = await AuthApi.login(
          email: _emailController.text.trim(),
          password: _passwordController.text,
          rememberMe: _keepSignedIn,
        );

        if (data['code'] == 200) {
          // 存储token
          Storage.setToken(data['data']['tokenValue']);
          // 获取并缓存用户信息
          await UserApi.updateUserInfo();
          // 跳转首页
          if (mounted) {
            Navigator.pushReplacementNamed(context, AppRoutes.home);
          }
        } else {
          if (mounted) {
            MessageUtil.toast(data['message'] ?? 'Login failed');
            // MessageUtil.success('MessageUtil.success');
            // MessageUtil.info('MessageUtil.info');
            // MessageUtil.warning('MessageUtil.warning');
            // MessageUtil.error('MessageUtil.error');
            // MessageUtil.toast('MessageUtil.toast');
            // // dismissAfterSeconds 消失时间，若为0，表示不消失
            // final closeToast = MessageUtil.toast(data['message'] ?? 'Login failed', dismissAfterSeconds: 0);
            // Future.delayed(const Duration(seconds: 10), closeToast);
            // final confirmed = await MessageUtil.showConfirmDialog(
            //   title: ('confirm_logout_title'),
            //   message: ('confirm_logout_message'),
            //   confirmText: ('log_out'),
            //   cancelText: ('cancel'),
            //   onConfirm: () {
            //     // MessageUtil.loading('加载中...', dismissAfterSeconds: 3);
            //     final closeLoading = MessageUtil.loading('加载中...');
            //     Future.delayed(const Duration(seconds: 5), closeLoading);
            //   },
            // );
            // debugPrint('confirmed $confirmed');
          }
        }
      } catch (e) {
        debugPrint('Login error: $e');
        if (mounted) {
          MessageUtil.error('Login failed. Please try again.');
        }
      } finally {
        if (mounted) setState(() => _isLoggingIn = false);
      }
    }
  }

  void _handleSocialLogin(String provider) {
    debugPrint('Social login with $provider');
    // TODO: 实现社交登录逻辑
  }
}
